package dnl.net.netclip;

import java.awt.AWTException;
import java.awt.Menu;
import java.awt.MenuItem;
import java.awt.PopupMenu;
import java.awt.SystemTray;
import java.awt.TrayIcon;
import java.awt.TrayIcon.MessageType;
import java.awt.event.ActionListener;

import javax.swing.ImageIcon;

/**
 * Centralizes any tray icon related operations.
 * 
 * @author <a href="mailto:daniel_or_else@yahoo.com">Daniel Or </a>
 */
public class TrayManagerImpl extends TrayManager{

	private SystemTray tray = SystemTray.getSystemTray();

	private TrayIcon ti;

	private PopupMenu rootPopup;

	private RootTrayMenu rootTrayMenu;
	
	/** Creates a new instance of TrayManageer */
	public TrayManagerImpl(String name, ImageIcon imageIcon) {
		super(name, imageIcon);
		rootPopup = new PopupMenu(name);
		
		ti = new TrayIcon(imageIcon.getImage(), name, rootPopup);
		try {
			tray.add(ti);
		} catch (AWTException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		rootTrayMenu = new RootTrayMenu();
	}

	@Override
	public TrayMenu getRoot() {
		return rootTrayMenu;
	}

	@Override
	public void displayMessage(String caption, String message) {
		ti.displayMessage(caption, message, MessageType.NONE);
	}

	@Override
	public void displayInfoMessage(String caption, String message) {
		ti.displayMessage(caption, message, MessageType.INFO);
	}

	@Override
	public void displayErrorMessage(String caption, String message) {
		ti.displayMessage(caption, message, MessageType.ERROR);
	}


	@Override
	public TrayMenu addMenuItemImpl(String path, boolean menu) {
		AWTTrayMenu trayMenu = new AWTTrayMenu(path, menu);
		return trayMenu;
	}
	
	@Override
	protected void addSeperator() {
		rootPopup.addSeparator();
	}
	
	private static class AWTTrayMenu extends TrayMenu{
		
		private MenuItem menu;
		
		public AWTTrayMenu(String path, boolean menu) {
			super(path);
			if(menu){
				this.menu = new Menu(getName());
			}
			else {
				this.menu = new MenuItem(getName());
			}
		}

		@Override
		public void addActionListener(ActionListener al) {
			menu.addActionListener(al);
		}
		
		
		@Override
		public void addMenuItem(TrayMenu childMenu) {
			AWTTrayMenu child = (AWTTrayMenu) childMenu;
			Menu concreteMenu = (Menu) menu;
			concreteMenu.add(child.menu);
		}

		@Override
		public void removeAllChildrenItems() {
			Menu concreteMenu = (Menu) menu;
			concreteMenu.removeAll();
		}
	}
	
	private class RootTrayMenu extends TrayMenu{
		private PopupMenu root;
		
		public RootTrayMenu() {
			super("/");
			root = TrayManagerImpl.this.rootPopup;
		}
		
		@Override
		public void addActionListener(ActionListener al) {
		}
		
		@Override
		public void addMenuItem(TrayMenu childMenu) {
			AWTTrayMenu child = (AWTTrayMenu) childMenu;
			root.add(child.menu);
		}

		@Override
		public void removeAllChildrenItems() {
		}
	}

}
